package com.example.mark.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.mark.common.Result;
import com.example.mark.entity.Administrator;
import com.example.mark.entity.User;
import com.example.mark.entity.UserData;
import com.example.mark.entity.UserFriendList;
import com.example.mark.mapper.AdministratorMapper;
import com.example.mark.mapper.UserDataMapper;
import com.example.mark.mapper.UserFriendListMapper;
import com.example.mark.mapper.UserMapper;
import com.example.mark.service.UserDataService;
import com.example.mark.service.UserService;
import com.example.mark.service.Impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
// @CrossOrigin 允许前端跨域请求
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private UserDataService userDataService;

    @Autowired
    private UserDataMapper userDataMapper;

    @Autowired
    private UserFriendListMapper userFriendListMapper;

    @Autowired
    private AdministratorMapper administratorMapper;

    @PostMapping("/login")
    public Result<User> login(@RequestBody User user){
//        user.toString();
        User one = userServiceImpl.isUserExists(user);
        System.out.println(one);
        // 查询不到用户
        if (one == null){
            return Result.error(user).addMsg("查询不到用户");
        }
        // 密码错误
        if(!one.getPassword().equals(user.getPassword())){
            return Result.error(user).addMsg("密码错误");
        }

        //登录成功
        return Result.success(one).addMsg("登陆成功");
    }

    @PostMapping("/register")
    @Transactional
    public Result<User> register(@RequestBody User user) {
        try {
            // 判断前端传来的数据是否正常
            if (user == null) {
                return Result.error(user).addMsg("请输入注册信息");
            }
            // 判断账号是否存在
            User one = userServiceImpl.isUserExists(user);
            if (one != null) {
                return Result.error(user).addMsg("用户账号已注册");
            }
            //校验密码长度
            if (!userServiceImpl.isPasswordStrong(user.getPassword())) {
                return Result.error(user).addMsg("密码长度至少为 8 位，包含数字、字母和特殊字符");
            }
            
            // 保存用户基本信息
            userService.save(user);

            // 获取新保存的用户信息（包含userId）
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getUsername, user.getUsername())
               .eq(User::getPassword, user.getPassword());
            User userSave = userService.getOne(lqw);

            // 创建用户数据记录
            UserData userData = new UserData();
            userData.setUserId(userSave.getUserId());
            userData.setCreateTime(LocalDateTime.now());

            userDataMapper.insert(userData);

            return Result.success(userSave).addMsg("注册成功！");
        } catch (Exception e) {
            throw new RuntimeException("注册用户时发生错误：" + e.getMessage());
        }
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user){
        // 判断前端传来的数据是否正常
        if (user==null){
            return Result.error("").addMsg("请输入修改啊账号信息");
        }
        // 判断账号是否存在
        User one = userServiceImpl.isUserExists(user);
        if (one!=null){
            return Result.error(user).addMsg("用户账号已注册");
        }
        //校验密码长度
        if (!userServiceImpl.isPasswordStrong(user.getPassword())){
            return Result.error(user).addMsg("密码长度至少为 8 位，包含数字、字母和特殊字符");
        }


        //一切正常
        if(userMapper.UpdateByUserId(user)){
            return Result.success(user).addMsg("用户修改信息成功！");
        }
        return Result.error("").addMsg("系统错误，请稍后重试！");
    }

    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestBody User user) {
        try {
            //判断用户是否存在
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getUsername, user.getUsername());
            User one = userService.getOne(lqw);
            
            if (one == null) {
                return Result.error("").addMsg("删除用户失败！用户不存在！");
            }

            int userId = one.getUserId();

            // 1. 删除用户数据
            LambdaQueryWrapper<UserData> userDataWrapper = new LambdaQueryWrapper<>();
            userDataWrapper.eq(UserData::getUserId, userId);
            userDataMapper.delete(userDataWrapper);

            // 2. 删除用户好友列表
            LambdaQueryWrapper<UserFriendList> friendListWrapper = new LambdaQueryWrapper<>();
            friendListWrapper.eq(UserFriendList::getUserId, userId);
            userFriendListMapper.delete(friendListWrapper);

            // 3. 删除用户基本信息
            if (userMapper.DeleteByUserId(userId)) {
                return Result.success("").addMsg("删除用户成功！");
            } else {
                throw new RuntimeException("删除用户基本信息失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("删除用户时发生错误：" + e.getMessage());
        }
    }

    @PostMapping("/updateUserData")
    public Result updateUserData(@RequestBody Map<String, Object> requestParams) {
        return userDataService.updateUserData(requestParams);
    }

    @PostMapping("/uploadPhoto")
    public Result uploadUserPhoto(@RequestParam("file") MultipartFile file) {
        return userDataService.uploadUserPhoto(file);
    }

    @GetMapping("/detail")
    public Result getUserDetail(@RequestBody Map<String, Object> requestParams) {
        int userId = (int) requestParams.get("userId");
        return userDataService.getUserDetail(userId);
    }

    @PostMapping("/adminLogin")
    public Result adminLogin(@RequestBody Map<String, Object> requestParams) {
        try {
            String username = (String) requestParams.get("username");
            String password = (String) requestParams.get("password");
            
            // 1. 先验证用户是否存在
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            User existUser = userServiceImpl.isUserExists(user);
            
            if (existUser == null) {
                return Result.error("用户不存在");
            }
            
            if (!existUser.getPassword().equals(password)) {
                return Result.error("密码错误");
            }
            
            // 2. 验证是否为管理员
            LambdaQueryWrapper<Administrator> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Administrator::getUserId, existUser.getUserId());
            Administrator admin = administratorMapper.selectOne(queryWrapper);
            
            if (admin == null) {
                return Result.error("该用户不是管理员");
            }
            
            // 3. 返回管理员信息
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userId", existUser.getUserId());
            resultMap.put("username", existUser.getUsername());
            resultMap.put("adminId", admin.getAdminId());
            
            return Result.success(resultMap).addMsg("管理员登录成功");
            
        } catch (Exception e) {
            return Result.error("管理员登录失败：" + e.getMessage());
        }
    }

}
